package com.cn.base.持久化;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @author: dlr
 * @data: 2019/8/18 22:54
 * @desc: 持久化发布订阅消费者
 */
public class persistent_topic_consumer {
    private final static String MQ_URL="tcp://192.168.10.20:61616";
    //点对点对队列名
    private final static String TOPIC_NAME="BASE_TOPIC";

    public static void main(String[] args) throws Exception{
        /*//连接工厂
        ActiveMQConnectionFactory factory=new ActiveMQConnectionFactory(MQ_URL);
        //获取连接
        Connection connection=factory.createConnection();
        //启动
        connection.start();
        //创建session
        //参数1:是否开启事务,参数2:签收模式
        Session session=connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //创建消息目的地发布订阅主题
        Topic topic = session.createTopic(TOPIC_NAME);
        //创建消费者
        MessageConsumer consumer = session.createConsumer(topic);

        while(true){
            //等待4s没有消息了就关闭
            TextMessage receive =(TextMessage)consumer.receive(4000l);
            if(receive!=null){
                System.err.println(receive.getText());
            }
            else{
                break;
            }
        }
        consumer.close();
        session.close();
        connection.close();
*/
        /*=============上边未设置持久化 对比上下的差异==================*/
        //连接工厂
        ActiveMQConnectionFactory factory=new ActiveMQConnectionFactory(MQ_URL);
        //获取连接
        Connection connection=factory.createConnection();
        //客户端id
        connection.setClientID("c-1");
        //创建session
        //参数1:是否开启事务,参数2:签收模式
        Session session=connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //创建消息目的地发布订阅主题
        Topic topic = session.createTopic(TOPIC_NAME);

        //主题的订阅者(topic,消费者的标注描述)
        TopicSubscriber subscriber=session.createDurableSubscriber(topic,"c-1发布订阅的消费者");
        //启动
        connection.start();
        //创建消费者
        TextMessage receive =(TextMessage)subscriber.receive();
        while(receive!=null){
            System.err.println(receive.getText());
            receive =(TextMessage)subscriber.receive();
        }
        subscriber.close();
        session.close();
        connection.close();

    }
}
